﻿using System;
using System.Windows;
using RG.Common;

namespace RG.Common.WPF.Dialogs
{
    public partial class DialogWindow : IView<DialogWindowVM>
    {
        public DialogWindow()
        {
            InitializeComponent();
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            AlignChildSize();
        }

        public DialogWindowVM Presenter
        {
            get { return (DialogWindowVM)DataContext; }
            set
            {
                DataContext = value;
                AlignChildSize();
            }
        }

        private void AlignChildSize()
        {
            if (Presenter == null || !(Presenter.Child is IChildView)) return;

            var lastChild = Presenter as IChildView;
            while (lastChild.Child is IChildView)
                lastChild = lastChild.Child as IChildView;

            // TODO Более красивое определение размера по умолчанию
            const int deltaHeight = 80;
            const int deltaWidth = 10;

            if (lastChild.ChildView is FrameworkElement)
            {
                var childView = (FrameworkElement)lastChild.ChildView;

                if (childView.MinHeight > Height - deltaHeight)
                    Height = childView.MinHeight + deltaHeight;
                if (childView.MinWidth > Width - deltaWidth) 
                    Width = childView.MinWidth + deltaWidth;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (DialogResult.HasValue && DialogResult.Value)
                return;
            e.Cancel = !Presenter.CanClose;
        }
    }
}
